/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    vector<TreeNode *> delNodes(TreeNode *root, vector<int> &to_delete)
    {
        if (root == nullptr)
        {
            return {};
        }
        unordered_set<int> toDeleteSet(to_delete.begin(), to_delete.end());
        using P = pair<TreeNode *, bool>;
        vector<TreeNode *> result;
        queue<P> q;
        q.push({root, true});

        while (!q.empty())
        {
            auto [tree, isRoot] = q.front();
            q.pop();

            if (toDeleteSet.count(tree->val))
            {
                if (tree->left != nullptr)
                {
                    q.push({tree->left, true});
                }
                if (tree->right != nullptr)
                {
                    q.push({tree->right, true});
                }
            }
            else
            {
                if (isRoot)
                {
                    result.push_back(tree);
                }
                if (tree->left != nullptr)
                {
                    q.push({tree->left, false});
                }
                if (tree->right != nullptr)
                {
                    q.push({tree->right, false});
                }
            }

            if (tree->left != nullptr && toDeleteSet.count(tree->left->val))
            {
                tree->left = nullptr;
            }
            if (tree->right != nullptr && toDeleteSet.count(tree->right->val))
            {
                tree->right = nullptr;
            }
        }
        return result;
    }
};